package com.bytedance.danmaku.render.engine.demo.danmu.bordertext

import android.graphics.Canvas
import android.graphics.Color
import android.graphics.LinearGradient
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.RectF
import android.graphics.Shader
import android.util.Log
import com.bytedance.danmaku.render.engine.control.DanmakuConfig
import com.bytedance.danmaku.render.engine.data.DanmakuData
import com.bytedance.danmaku.render.engine.demo.danmu.project.GradientChangeDiggDanmaku
import com.bytedance.danmaku.render.engine.demo.danmu.project.GradientChangeDiggDanmakuDrawItem
import com.bytedance.danmaku.render.engine.demo.utils.DRAW_TYPE_OFFICIAL_ADVANCED
import com.bytedance.danmaku.render.engine.demo.utils.DensityUtils.dp2px
import com.bytedance.danmaku.render.engine.demo.utils.DensityUtils.sp2px
import com.bytedance.danmaku.render.engine.demo.utils.dp
import com.bytedance.danmaku.render.engine.render.draw.DrawItem
import com.bytedance.danmaku.render.engine.render.draw.IDrawItemFactory
import com.bytedance.danmaku.render.engine.render.draw.bitmap.BitmapData
import com.bytedance.danmaku.render.engine.render.draw.bitmap.BitmapDrawItem
import com.bytedance.danmaku.render.engine.utils.HIGH_REFRESH_MAX_TIME
import kotlin.math.max

/**
 * @Description:自定义官方弹幕
 * @Author yanxin
 * @Date:  2025/8/21
 */

class OfficialDanmaku : DanmakuData() {
    var officialIcon: BitmapData? = null
    var gradientChangeDiggDanmaku: GradientChangeDiggDanmaku? = null
    var gradientColors: IntArray? = intArrayOf() //自定义颜色数组
    var useGradient = false
    override var drawType: Int = DRAW_TYPE_OFFICIAL_ADVANCED
}

class OfficialDanmakuDrawItem : DrawItem<OfficialDanmaku>() {

    // 渐变相关变量
    private var gradient: LinearGradient? = null
    private var lastText: String? = null
    private val gradientMatrix = Matrix()
    private var lastGradientColors: IntArray? = null
    private val mRoundBgRectF = RectF()
    private val mRoundBgPaint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.DITHER_FLAG)
    private var gradientTextColors = mutableListOf<Int>()
    private var mPaddingLeft = dp2px(3F) //左间距
    private var mPaddingRight = dp2px(10f) //右间距
    private var padding = dp2px(3f) * 2
    private var useGradient = false
    private var drawDiggBgWidth = 0f
    private var mMargin=dp2px(30f)
    // 创建临时画笔获取文字度量
    val paint = Paint().apply {
        textSize = sp2px(16F).toFloat()
    }

    val fontMetrics = paint.fontMetrics
    override var x: Float = 0F
        set(value) {
            field = value
            updateXY()
        }
    override var y: Float = 0F
        set(value) {
            field = value-20 //矫正轨道
            updateXY()
        }
    private val mOfficialIconItem: BitmapDrawItem = BitmapDrawItem()
    private val mGradientChangeDiggDanmakuDrawItem: GradientChangeDiggDanmakuDrawItem =
        GradientChangeDiggDanmakuDrawItem()

    override fun getDrawType(): Int {
        return DRAW_TYPE_OFFICIAL_ADVANCED
    }

    override fun onMeasure(config: DanmakuConfig) {
        mOfficialIconItem.measure(config)
        mGradientChangeDiggDanmakuDrawItem.measure(config)
        drawDiggBgWidth =
            mOfficialIconItem.width + mGradientChangeDiggDanmakuDrawItem.width + mPaddingLeft + mPaddingRight
        width = drawDiggBgWidth + mPaddingLeft+mMargin
        height = max(mOfficialIconItem.height, mGradientChangeDiggDanmakuDrawItem.height) + padding
        updateXY()
    }

    override fun onDraw(canvas: Canvas, config: DanmakuConfig) {
        if (useGradient) {
            drawDiggBg(canvas)
        }
        mOfficialIconItem.draw(canvas, config)
        mGradientChangeDiggDanmakuDrawItem.draw(canvas, config)
    }

    override fun onBindData(data: OfficialDanmaku) {
        useGradient = data.useGradient
        if (useGradient) {
            data.gradientColors?.let {
                if (it.size > 1) {
                    gradientTextColors = it.toMutableList()
                } else {
                    //渐变色开始颜色 默认ui上蓝色
                    gradientTextColors.add(Color.parseColor("#3399FF"))
                    gradientTextColors.add(Color.parseColor("#086DFF"))
                }
            }
        }
        data.officialIcon?.let {
            mOfficialIconItem.bindData(it)
        }
        data.gradientChangeDiggDanmaku?.let {
            mGradientChangeDiggDanmakuDrawItem.bindData(it)
        }
    }

    private fun drawDiggBg(canvas: Canvas) {
        handleGradient(data?.gradientChangeDiggDanmaku?.mTextData?.text.toString())
        //边框样式
        mRoundBgPaint.setStyle(Paint.Style.FILL); // 设置绘制样式为描边
        mRoundBgPaint.setStrokeWidth(3f);  // 设置边框宽度
        mRoundBgPaint.setColor(Color.WHITE);         // 设置边框颜色
        mRoundBgRectF.set(
            x,
            y,
            x + drawDiggBgWidth + mPaddingRight,
            y + height
        )
        canvas.drawRoundRect(mRoundBgRectF, height / 2, height / 2, mRoundBgPaint)
    }

    private fun updateXY() {
        mOfficialIconItem.x = x + mPaddingLeft
        mOfficialIconItem.y = y + (height - mOfficialIconItem.height) / 2
        mGradientChangeDiggDanmakuDrawItem.x = x + mOfficialIconItem.width + mPaddingLeft
        mGradientChangeDiggDanmakuDrawItem.y =
            y + (height - max(
                mOfficialIconItem.height,
                mGradientChangeDiggDanmakuDrawItem.height
            )-padding) / 2-(fontMetrics.ascent + fontMetrics.descent) / 2

    }

    private fun handleGradient(text: String) {
        val colors = gradientTextColors.toIntArray()
        // 只在以下情况重新创建渐变：
        // 1. 渐变不存在
        // 2. 文字内容变化
        // 3. 文字宽度变化
        // 4. 渐变色变化
        if (gradient == null &&
            !text.contentEquals(lastText) &&
            !colors.contentEquals(lastGradientColors)
        ) {
            gradient = LinearGradient(
                0f, 0f, width, 0f, // 渐变区域匹配文字宽度
                colors,
                null,
                Shader.TileMode.CLAMP
            ).apply {
                // 保存当前状态
                lastText = text
                lastGradientColors = colors.copyOf()
            }
        }
        // 更新渐变位置（每次绘制都执行）
        gradientMatrix.reset()
        gradientMatrix.postTranslate(x, 0f) // 根据当前x位置偏移
        gradient?.setLocalMatrix(gradientMatrix)
        mRoundBgPaint.shader = gradient
    }

    override fun recycle() {
        super.recycle()
        mOfficialIconItem.recycle()
        mGradientChangeDiggDanmakuDrawItem.recycle()
    }
}

class OfficialDanmakuFactory : IDrawItemFactory {

    override fun getDrawType(): Int {
        return DRAW_TYPE_OFFICIAL_ADVANCED
    }

    override fun generateDrawItem(): DrawItem<out DanmakuData> {
        return OfficialDanmakuDrawItem()
    }

}
